﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class TranformExtend
{

    /// <summary>
    /// 拓展方法，销毁自身所有子对象
    /// </summary>
    /// <param name="transform"></param>
    public static void DestroyChildren(this Transform transform)
    {
        int childCount = transform.childCount;
        for (int i = 0; i < childCount; i++)
        {
            GameObject.Destroy(transform.GetChild(i).gameObject);
        }
    }

    public static void DestroyChildrenImmediate(this Transform transform)
    {
        for (int childIndex = transform.childCount - 1; childIndex >= 0; childIndex--)
        {
            GameObject.DestroyImmediate(transform.GetChild(childIndex).gameObject);
        }

    }

    public static Transform GetLastChild(this Transform transform)
    {
        if (transform.childCount <= 0) return null;
        return transform.GetChild(transform.childCount - 1);
    }

    public static Transform GetFirstChild(this Transform transform)
    {
        return transform.GetChild(0);
    }

    /// <summary>
    /// 根据对象名字排序子对象
    /// </summary>
    /// <param name="transform"></param>
    public static void SortChildrenByName(this Transform transform, bool reverse = false)
    {
        var childList = new List<Transform>();
        foreach (Transform child in transform)
        {
            childList.Add(child);
        }

        childList.Sort((a, b) => a.name.CompareTo(b.name) * (reverse ? -1 : 1));

        for (int i = 0; i < childList.Count; i++)
        {
            var child = childList[i];
            child.SetSiblingIndex(i);
        }
    }
}
